package com.example.aircraftwar2024.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

import com.example.aircraftwar2024.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeoutException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private boolean music=true;
    private Socket socket;
    AlertDialog dialog_; //对话框
    private Handler handler;
    public static PrintWriter writer = null;
    public static boolean online = false;
    public static int score_for_enemy = -1;
    public static boolean enemy_valid = true;
    public static boolean send_death = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        ActivityManager.getActivityManager().addActivity(this);

        //创建对话框
        AlertDialog.Builder builder_ = new AlertDialog.Builder(this);
        setBuilder_(builder_);
        dialog_ = builder_.create();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button startBtn = (Button) findViewById(R.id.startBtn);
        Button onlineBtn = (Button) findViewById(R.id.onlineBtn);
        Button musicOnBtn = (Button) findViewById(R.id.musicOnBtn);
        Button musicOffBtn = (Button) findViewById(R.id.musicOffBtn);

        startBtn.setOnClickListener(this);
        musicOnBtn.setOnClickListener(this);
        musicOffBtn.setOnClickListener(this);
        onlineBtn.setOnClickListener(this);

        handler = new Handler(getMainLooper()){
            //当数据处理子线程更新数据后发送消息给UI线程，UI线程更新UI
            @Override
            public void handleMessage(Message msg){
                if(msg.what == 1){
                    //TODO
                    dialog_.hide();

                    Intent intent = new Intent(MainActivity.this, OnlineActivity.class);
                    intent.putExtra("gameType", OfflineActivity.GameMode.HARD.ordinal());
                    intent.putExtra("music", music);
                    startActivity(intent);

                }
            }
        };
    }
    @Override
    public void onClick(View v){
        if (v.getId()==R.id.startBtn){
            enemy_valid = false;
            Intent intent = new Intent(MainActivity.this, OfflineActivity.class);
            intent.putExtra("music",music);
            startActivity(intent);
        }else if(v.getId() == R.id.onlineBtn){
            online = true;
            enemy_valid = true;
            dialog_.show();
            new Thread(new NetConn(handler)).start();
        }
        else if (v.getId()==R.id.musicOffBtn) music=false;
        else music=true;
    }
    public boolean getMusic(){
        return music;
    }

    private void setBuilder_(AlertDialog.Builder builder_){
        builder_.setMessage("正在寻找对手...");
        builder_.setTitle("联机模式");

    }

    protected class NetConn extends Thread{
        private BufferedReader in;
        private Handler toClientHandler;
        public NetConn(Handler myHandler){
            this.toClientHandler = myHandler;
        }

        @Override
        public void run(){
            try{
                socket = new Socket();

                while (!socket.isConnected()){
                    System.out.println("等待链接中");
                    try {
                        socket.connect(new InetSocketAddress
                                ("10.250.189.228", 9999), 5000);
                    }catch (SocketTimeoutException e) {
                        socket = new Socket();
                        continue;
                    }
                    break;
                }

                in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
                writer = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(
                                socket.getOutputStream(), "utf-8"
                        )), true);
                System.out.println("Connected");
                writer.println("Coming");
                this.listener();
            } catch(UnknownHostException ex){
                ex.printStackTrace();
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }
        public void listener(){
            TimerTask task = new TimerTask() {
                @Override
                public void run(){
                    String fromserver = null;
                    try{
                        fromserver = in.readLine();
                        //发送消息给UI线程
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = fromserver;
                        if (fromserver.equals("you are in game!")) {
                            toClientHandler.sendMessage(msg);
                        }else if (fromserver.equals("XCH ALIVE")) {
                            enemy_valid = false;
                        } else {
                            score_for_enemy = Integer.parseInt(fromserver);
                        }

                    }catch (IOException ex){
                        ex.printStackTrace();
                    }
                }
            };
            Timer timer = new Timer();
            // 定义开始等待时间  --- 等待 5 秒
            // 1000ms = 1s
            long delay = 0;
            // 定义每次执行的间隔时间
            long intevalPeriod = 10;
            // schedules the task to be run in an interval
            // 安排任务在一段时间内运行
            timer.scheduleAtFixedRate(task, delay, intevalPeriod);
        }
    }
}